import React from 'react';
import util from 'util';
import {Button, Table, Modal, Form, message} from 'antd';
import {SearchDemo, RightButton, ColsEdit} from 'kpl';
import sys_dict from "sys_dict";

class A102 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tblSource: [],
            xztblSource: [],
            searchParams: {
                rolename: "",
                roletype: "",
                descript: "",
                ylData:[],
                "page": 1,
                "rows": sys_dict.defaultPageSize.toString()
            },
            totalCount: 0,
            xztotalCount: 0,
            isLoading: false
        }
        this.tempgroup_id = "";
    }

    //默认查询
    componentDidMount() {
        util.httpRequest({

            type: "POST", url: 'manage020008.json', params: {},
            success: function (result) {
                //console.log("manage020008.json-->", result);
                let arr = [];
                result.group_list.forEach(function (i) {
                    var obj = {};
                    obj.itemkey = i.group_id;
                    obj.itemval = i.group_name;
                    arr.push(obj);
                });
                this.setState({ylData: arr});
            }.bind(this),
            complete: function () {
                this.setState({
                    isLoading: false
                })
            }.bind(this)
        });
        let params = this.state.searchParams;
        this.refresh(params);
    }

    refresh(paramdic) {
        this.setState({isLoading: true});
        util.httpRequest({
            type: "POST", url: 'manage020007.json', params: paramdic, plattype: '', success: function (result) {
                if (result.ret_code == "0000") {
                    this.setState({
                        tblSource: result.group_list,
                        totalCount: result.total
                    });
                }
            }.bind(this),
            complete: function () {
                this.setState({
                    isLoading: false
                })
            }.bind(this)
        });
    }

    search(params) {
        console.log(this);
        params.page = "1";
        params.rows = sys_dict.defaultPageSize.toString();
        this.setState({
            searchParams: params
        });
        this.refresh(params);
    }

    onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
        var params = this.state.searchParams;
        params.rows = pageSize;
        params.page = current;
        this.setState({searchParams: params});
        this.refresh(params);
    }

    onChange(page) {
        console.log(page);
        var params = this.state.searchParams;
        params.page = page;
        this.setState({searchParams: params});
        this.refresh(params);
    }

    getTableConfig(){
    	
        const pagination = {
            total: this.state.totalCount,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: sys_dict.pageSizeOptions,
            defaultPageSize: sys_dict.defaultPageSize,
            onShowSizeChange: this.onShowSizeChange.bind(this),
            onChange: this.onChange.bind(this)
        };
		 let tableConfig={};
		 
		 tableConfig.queryConfig={ 
		 
            searchTitle: "团队信息查询",
            searchInit: {
               
            },
            searchField: [
                [
                    {propsname: "所属团队", propsKey: "group_name",propsType: "select",key: "1111",optionData: this.state.ylData,selectFun:this.selectsearchFun.bind(this)},
                    {propsname: "团队状态：", propsKey: "group_status", propsType: "select",optionData:[{itemkey:"1",itemval:"启用"},{itemkey:"0",itemval:"停用"}], key: "2222"}
                ]
            ]
        };


        tableConfig.resultConfig={
            pagination: pagination,
            loading: this.state.isLoading,
            dataSource: this.state.tblSource,
            columns: [{
                title: '序号',
                dataIndex: 'index',
                render: function (value, data, rowIndex) {
                    return rowIndex+1;
                }
            }, {
                title: '团队名称',
                dataIndex: 'group_name',
                key: 'group_name'
            },{
                title: '下属小组数',
                dataIndex: 'sub_group_nums',
                key: 'sub_group_nums',
            }, {
                title: '实际参赛人数',
                dataIndex: 'real_all_nums',
                key: 'real_all_nums'
            }, {
                title: '工会提供人数',
                dataIndex: 'all_nums',
                key: 'all_nums'
            }, {
                title: '团队状态',
                dataIndex: 'group_status',
                key: 'group_status',
                render: (text, data, index) => (
                    <span>{data.group_status == "1" ?
                        <span>正常</span>:<span>停用</span>}
                        </span>
                )
            },{
                title: '操作',
                dataIndex: 'caozuo',
                 render: (text, data, index) => (
                    <span>
                        <a onClick={this.row_update.bind(this, data, index)}>修改</a>
                        <span className="ant-divider"></span>
                        <a onClick={this.row_detail.bind(this, data, index)}>详情</a>
                        <span className="ant-divider"></span>
                        <a onClick={this.row_modifyStatus.bind(this, data, index)}>
                            {data.group_status=="1"?<span>停用</span>:<span>启用</span>}
                        </a>
                        <span className="ant-divider"></span>
                        <a onClick={this.delete.bind(this, data, index)}>删除</a>
                    </span>
                    )
            }]
        };
        return tableConfig;
    }

    getxzTableConfig(){

        const xzpagination = {
            total: this.state.xztotalCount,
            showSizeChanger: false,
            showQuickJumper: false,
            pageSizeOptions: sys_dict.pageSizeOptions,
            defaultPageSize: sys_dict.defaultPageSize,
        };
        let xztableConfig={};
        xztableConfig.resultConfig={
            pagination: xzpagination,
            loading: this.state.isLoading,
            dataSource: this.state.xztblSource,
            columns: [{
                title: '序号',
                dataIndex: 'index',
                render: function (value, data, rowIndex) {
                    return rowIndex+1;
                }
            }, {
                title: '小组id',
                dataIndex: 'sub_group_id',
                key: 'sub_group_id'
            },{
                title: '小组名称',
                dataIndex: 'sub_group_name',
                key: 'sub_group_name',
            }, {
                title: '小组内人数',
                dataIndex: 'count_user_id',
                key: 'count_user_id'
            }, {
                title: '工会提供的人数',
                dataIndex: 'all_nums',
                key: 'all_nums'
            }, {
                title: '创建时间',
                dataIndex: 'crt_date_time',
                key: 'crt_date_time'
            },{
                title: '操作',
                dataIndex: 'caozuo',
                render: (text, data, index) => (
                    <span>
                        <a onClick={this.row_updatexz.bind(this, data, index)}>修改</a>
                        <span className="ant-divider"></span>
                        <a onClick={this.deletexz.bind(this, data, index)}>删除</a>
                    </span>
                )
            }]
        };
        return xztableConfig;
    }

    selectsearchFun(value) {
        util.httpRequest({

            type: "POST", url: 'manage020011.json', params: {group_id: value},
            success: function (result) {
                console.log("manage020011.json-->", result);
                let arr = [];
                result.sub_group_list.forEach(function (i) {
                    var obj = {};
                    obj.itemkey = i.group_id;
                    obj.itemval = i.group_name;
                    arr.push(obj);
                });
                this.setState({
                    xzData: arr,
                });
            }.bind(this)
        });
    }

    //显示团队详情
    row_detail(record, type, e){
        this.tempgroup_id = record.group_id;
        util.httpRequest({
            type: "POST", url: 'manage020028.json', params: {group_id: record.group_id},
            success: function (result) {
                console.log("manage020028.json-->", result);
                this.setState({
                    xztblSource: result.sub_group_list,
                    xztotalCount: result.sub_group_list.length,
                    tddetailVisible: true,
                });
            }.bind(this)
        });
    }
    //删除团队
    delete(record, type){
        util.httpRequest({
            type: "POST", url: 'manage020006.json', params: {group_id: record.group_id},
            success: function (result) {
                console.log("manage020006.json-->", result);
                message.success("删除团队成功");
            }.bind(this)
        });
        let params = this.state.searchParams;
        this.refresh(params);
    }
    //删除小组
    deletexz(record, type){
        util.httpRequest({
            type: "POST", url: 'manage020027.json', params: {sub_group_id: record.sub_group_id},
            success: function (result) {
                console.log("manage020027.json-->", result);
                message.success("删除小组成功");
                this.handleCancel();
            }.bind(this)
        });
    }

    //新增团队名称
    row_add(){
        this.setState({
            modalVisible: false,
            editVisible:false,
            xzeditVisible:false,
            tddetailVisible: false,
            operateData: [],
            addtdVisible: true,
            operateType: 'ADD',
            modalTitle: "新增团队"
        }, function () {

        });
    }
    //新增小组
    row_addxz(){
        this.setState({
            modalVisible: false,
            editVisible:false,
            tddetailVisible: false,
            xzeditVisible:false,
            operateData: [],
            addtdVisible: false,
            addxzVisible: true,
            operateType: 'ADD',
            modalTitle: "新小组"
        }, function () {

        });
    }

    //修改团队名称
    row_update(record, type){
        this.setState({
            modalVisible: false,
            operateData: record,
            addtdVisible: false,
            tddetailVisible: false,
            xzeditVisible:false,
            editVisible:true,
            operateType: 'EDIT',
            modalTitle: "修改团队名称"
        }, function () {
            var {setFieldsValue} = this.refs.editForm.getForm();
            setFieldsValue(record);
            console.log("record.group_name"+record.group_name);
        });
    }
    //修改小组名称
    row_updatexz(record, type){
        this.setState({
            modalVisible: false,
            operateData: record,
            addtdVisible: false,
            addxzVisible:false,
            tddetailVisible: false,
            editVisible:false,
            xzeditVisible:true,
            operateType: 'EDIT',
            modalTitle: "修改小组名称"
        }, function () {
            var {setFieldsValue} = this.refs.editxzForm.getForm();
            setFieldsValue(record);
        });
    }

    //更变团队状态
    row_modifyStatus(record, type){
        var me = this;
        if (type == "0") {
            record.status="0";
            var sContent="若将["+record.group_name+"] 状态改为禁用吗？";
            var sOkText="确认停用";
            var sCancelText="不停用";
        } else{
            record.status="1";
            var sContent="确认要将["+record.group_name+"]由禁用状态改为正常吗？";
            var sOkText="确认启用";
            var sCancelText="不启用";
        }

        Modal.confirm({
            title:sOkText,
            content: sContent,
            okText: sOkText,
            cancelText: sCancelText,
            onOk: function () {
                util.httpRequest({
                    type: "POST",
                    url: 'manage020023.json',
                    params: {
                        group_id: record.group_id,
                        group_status: record.group_status=='0'?'1':'0'
                    },
                    success: function (result) {
                        me.refresh(me.searchParams);
                    }.bind(this)
                });
            }
        });
    }

    handleCancel() {
        this.setState({
            modalVisible: false,
            addtdVisible: false,
            addxzVisible :false,
            editVisible: false,
            xzeditVisible:false,
            tddetailVisible: false,
        });
    }

    handlexzCancel() {
        this.setState({
            modalVisible: false,
            addtdVisible: false,
            addxzVisible: false,
            editVisible: false,
            xzeditVisible:false,
            tddetailVisible: true,
        });
    }


    row_deleteRecord(record, type, e) {
		var me = this;
        var sContent="确认要删除该团队吗？";
        var sOkText="确认删除";
        var sCancelText="不删除";
        
        Modal.confirm({
            title:sOkText,
            content: sContent,
            okText: sOkText,
            cancelText: sCancelText,
            onOk: function () {
                    util.httpRequest({
                        type: "POST",
                        url: 'manage020006.json',
                        plattype: '',
                        params: record,
                        success: function (result) {
                            me.refresh(me.state.searchParams);
                        }.bind(this)
                    });
                }
            });
	}

   add_display() {
        this.setState({
            modalVisible: true,
            operateType: "ADD",
            operateData: {},
            modalTitle: "新增"
        }, function () {
            var form = this.refs.addForm.getForm();
            form.resetFields();
        });
    }
 
  getAddFormConfig(){
    	const createConfig = {
            operateTitle: "团队文件上传：请从本地选择后缀为.xls或者.xlsx的团队信息文件上传",
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 12, wrapperCol: 12},
            operateField: [
                 [
                    {
                        propsname: "选择团队信息文件：",
                        propsKey: "content",
                        propsType: "fileupload",
                        uploadCustomProps:{accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"},
                        key: "333",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ]
            ]
        };
        return createConfig;
   }

    getAddxzFormConfig(){
        const createConfig = {
            operateTitle: this.state.modalTitle,
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 4, wrapperCol: 12},
            operateField: [
                [{
                    propsname: "小组名称：", propsKey: "sub_group_name", propsType: "input", key: "121",
                }],
                [{
                    propsname: "工会提供的人数：", propsKey: "all_nums", propsType: "input", key: "122",
                }],
            ]
        };
        return createConfig;
    }

    getAddtdFormConfig(){
        const createConfig = {
            operateTitle: this.state.modalTitle,
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 4, wrapperCol: 12},
            operateField: [
                [{
                    propsname: "团队名称：", propsKey: "group_name", propsType: "input", key: "111",
                }],
                [{
                    propsname: "工会提供的人数：", propsKey: "all_nums", propsType: "input", key: "112",
                }],
            ]
        };
        return createConfig;
    }

    geteditFormConfig(){
        const createConfig = {
            operateTitle: this.state.modalTitle,
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 4, wrapperCol: 12},
            operateField: [
                [{
                    propsname: "团队名称：", propsKey: "new_group_name", propsType: "input", key: "113",
                }],
                [{
                    propsname: "工会提供的人数：", propsKey: "new_all_nums", propsType: "input", key: "114",
                }],
            ]
        };
        return createConfig;
    }

    geteditxzFormConfig(){
        const createConfig = {
            operateTitle: this.state.modalTitle,
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 4, wrapperCol: 12},
            operateField: [
                [{
                    propsname: "小组名称：", propsKey: "sub_group_name", propsType: "input", key: "115",
                }],
                [{
                    propsname: "工会提供的人数：", propsKey: "all_nums", propsType: "input", key: "116",
                }],
            ]
        };
        return createConfig;
    }

    //确定新增团队
    addtd_save(values){
        console.log("operateType"+this.state.operateType);
        var form = this.refs.addtdForm.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
                this.handleCancel();
                return;
            }
            console.log("this.state.operateData"+this.state.operateData);
            //关闭窗口
            var obj = {};
            if (values.group_name != undefined && values.group_name != "") {
                obj.group_name = values.group_name;
            } else{
                message.error("团队名称不能为空");
                return;
            }
            obj.all_nums = values.all_nums;

                util.httpRequest({
                    type: "POST",
                    url: 'manage020021.json',
                    plattype: '',
                    params: obj,
                    success: function (result) {
                        if(result.ret_code=="0000"){
                            message.success("新增团队成功");
                            this.handleCancel();
                            this.componentDidMount();
                        }else{
                            message.error("处理失败");
                        }
                    }.bind(this)
                });
        });
    }
    //确定新增小组
    addxz_save(values){
        var form = this.refs.addxzForm.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
                this.handleCancel();
                return;
            }
            console.log("this.state.operateData"+this.state.operateData);
            //关闭窗口
            var obj = {};
            if (values.sub_group_name != undefined && values.sub_group_name != "") {
                obj.sub_group_name = values.sub_group_name;
            } else{
                message.error("团队名称不能为空");
                return;
            }
            obj.all_nums = values.all_nums;
            obj.group_id = this.tempgroup_id;
            util.httpRequest({
                type: "POST",
                url: 'manage020024.json',
                plattype: '',
                params: obj,
                success: function (result) {
                    if(result.ret_code=="0000"){
                        message.success("新增小组成功");
                        this.handleCancel();
                    }else{
                        message.error("处理失败");
                    }
                }.bind(this)
            });
        });
    }

    edit_save(values){
        var form = this.refs.editForm.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
                this.handleCancel();
                return;
            }
            //关闭窗口
            var obj = {};
            if (values.new_group_name != undefined && values.new_group_name != "") {
                obj.new_group_name = values.new_group_name;
            } else{
                message.error("团队名称不能为空");
                return;
            }
            obj.new_all_nums = values.new_all_nums;
            obj.group_id = this.state.operateData.group_id;
                util.httpRequest({
                    type: "POST",
                    url: 'manage020022.json',
                    plattype: '',
                    params: obj,
                    success: function (result) {
                        if(result.ret_code=="0000"){
                            message.success("修改团队成功");
                            this.handleCancel();
                            this.componentDidMount();
                        }else{
                            message.error("处理失败");
                        }
                    }.bind(this)
                });
        });
    }

    //确定修改
    editxz_save(values){
        var form = this.refs.editxzForm.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
                this.handleCancel();
                return;
            }
            console.log("");
            //关闭窗口
            var obj = {};
            if (values.sub_group_name != undefined && values.sub_group_name != "") {
                obj.new_sub_group_name = values.sub_group_name;
            } else{
                message.error("小组名称不能为空");
                return;
            }
            obj.new_all_nums = values.all_nums;
            obj.sub_group_id = this.state.operateData.sub_group_id;
            util.httpRequest({
                type: "POST",
                url: 'manage020025.json',
                plattype: '',
                params: obj,
                success: function (result) {
                    if(result.ret_code=="0000"){
                        message.success("修改小组成功");
                        this.handleCancel();
                    }else{
                        message.error("处理失败");
                    }
                }.bind(this)
            });
        });
    }
    
    add_save(values) {
        var form = this.refs.addForm.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
            	 this.handleCancel();
                return;
            }
            console.log(values);
            //关闭窗口
           if (values.content != undefined && values.content != "") {
                    var obj = {};
                    obj.resource_url = values.content[0].response.resource_url;
                    obj.file_name = values.content[0].response.file_name;
                    obj.resource_id = values.content[0].response.resource_id;
           } else{
           		message.error("请先选择文件上传");
           		this.handleCancel();
           		return;
           }
           
           util.httpRequest({
               type: "POST",
               url: 'manage020005.json',
               plattype: '',
               params: obj,
               success: function (result) {
                   if(result.ret_code=="0000"){
                       message.success("处理成功");
                       this.handleCancel();
                       this.componentDidMount();
                   }else{
                       message.error("处理失败");
                   }
               }.bind(this)
           });
        });
    }

    render() {
    	let tableConfig = this.getTableConfig();
        let xztableConfig = this.getxzTableConfig();
        let addFormConfig =this.getAddFormConfig();
        let addtdFormConfig =this.getAddtdFormConfig();
        let addxzFormConfig =this.getAddxzFormConfig();
        let editFormConfig =this.geteditFormConfig();
        let editxzFormConfig =this.geteditxzFormConfig();
        return (
            <div>
                <SearchDemo search={this.search.bind(this)} searchConfig={tableConfig.queryConfig}></SearchDemo>
                <RightButton styleName="addBtn" propsKey="121" btnTxt="+  新增团队    " oprate={this.row_add.bind(this)}> </RightButton>
                <Table {...tableConfig.resultConfig}></Table>
                <Modal visible={this.state.modalVisible} title={addFormConfig.operateTitle} width="50%"
                               closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.add_save.bind(this)}>确定上传</Button>
                        ]}>
                		<ColsEdit ref="addForm" key={Math.random()}  config={addFormConfig}></ColsEdit>
                </Modal>
                <Modal visible={this.state.addtdVisible} title={addtdFormConfig.operateTitle} width="50%"
                       closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.addtd_save.bind(this)}>确定</Button>
                        ]}>
                    <ColsEdit ref="addtdForm" key={Math.random()}  config={addtdFormConfig}></ColsEdit>
                </Modal>
                <Modal visible={this.state.addxzVisible} title={addxzFormConfig.operateTitle} width="50%"
                       closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handlexzCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.addxz_save.bind(this)}>确定</Button>
                        ]}>
                    <ColsEdit ref="addxzForm" key={Math.random()}  config={addxzFormConfig}></ColsEdit>
                </Modal>
                <Modal visible={this.state.editVisible} title={editFormConfig.operateTitle} width="50%"
                       closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.edit_save.bind(this)}>确定</Button>
                        ]}>
                    <ColsEdit ref="editForm" key={Math.random()}  config={editFormConfig}></ColsEdit>
                </Modal>
                <Modal visible={this.state.tddetailVisible} width="80%"
                       closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>关闭</Button>
                        ]}>
                    <RightButton styleName="addBtn" propsKey="131" btnTxt="+  新增小组    " oprate={this.row_addxz.bind(this)}> </RightButton>
                    <Table {...xztableConfig.resultConfig}></Table>
                </Modal>
                <Modal visible={this.state.xzeditVisible} title={editxzFormConfig.operateTitle} width="50%"
                       closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handlexzCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.editxz_save.bind(this)}>确定</Button>
                        ]}>
                    <ColsEdit ref="editxzForm" key={Math.random()}  config={editxzFormConfig}></ColsEdit>
                </Modal>
            </div>
        );
    }
}

export default A102;